package testDemo;

import java.util.LinkedList;
import java.util.Queue;

public class MyStack {
    private Queue<Integer> queue1 ;
    private Queue<Integer> queue2 ;
    public MyStack() {
    queue1 = new LinkedList<>();
    queue2 = new LinkedList<>();
    }

    public void push(int x) {
        if (empty()){
            queue1.offer(x);
            return;
        }
        if (!queue1.isEmpty()){
            queue1.offer(x);
        }else {
            queue2.offer(x);
        }
    }

    public int pop() {
        if (empty()){
            return -1;
        }
//        找出不为空的队列，出size-1个元素
        if (!queue1.isEmpty()){
            int size = queue1.size();
            for (int i = 0; i < size-1; i++) {
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        }else {
            int size = queue2.size();
//          for (int i = 0; i < queue2.size()-1; i++)
//          以上写法错误，因为queue2.size()始终在变化
            for (int i = 0; i < size-1; i++) {
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        }
    }

    public int top() {
        if (empty()){
            return -1;
        }
        int tmp = -1;
        if (!queue1.isEmpty()){
            int size = queue1.size();
            for (int i = 0; i < size-1; i++) {
                queue2.offer(queue1.poll());
            }
            tmp = queue1.poll();
            queue2.offer(tmp);
            return tmp;
        }else {
            int size = queue2.size();
            for (int i = 0; i < size-1; i++) {
                queue1.offer(queue2.poll());
            }
            tmp = queue2.poll();
            queue1.offer(tmp);
            return tmp;
        }
    }

    public boolean empty() {
        if (queue1.isEmpty() && queue2.isEmpty()){
            return true;
        }
        return false;
    }
}
